package com.song.gateway.util;

import com.alibaba.fastjson.JSONObject;
import com.song.common.constant.RedisConstants;
import com.song.common.model.WhiteList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class WhiteListUtil {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public List<WhiteList> getWhiteList(){
        List<WhiteList> whiteLists = new ArrayList<>();
        List<Object> values = redisTemplate.opsForHash().values(RedisConstants.WHITE_LIST_KEY);
        if (!CollectionUtils.isEmpty(values)){
            whiteLists = values.stream().map(obj -> {
                return JSONObject.parseObject(obj.toString(), WhiteList.class);
            }).collect(Collectors.toList());
        }
        return whiteLists;
    }

    public boolean isWhiteList(String url){
        List<WhiteList> whiteList = getWhiteList();
        for (WhiteList wl : whiteList) {
            if (url.contains(wl.getPath())){
                return true;
            }
        }
        return false;
    }
}
